package com.sb.framework.event.listener;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

import org.springframework.context.ApplicationListener;

import com.sb.framework.event.SystemErrorEvent;
import com.sb.framework.exception.BusinessException;
import com.sb.framework.exception.SystemErrorException;
import com.sb.framework.util.DateUtils;
import com.sb.framework.util.PathUtil;

public class SystemErrorEventListener implements ApplicationListener<SystemErrorEvent> {

	private static final String	DATA_FORMAT	= DateUtils.dateTimePattern;

	private static final String	SEPARATOR	= " ";

	private static final String	LOG_NAME	= "sys_err.log";

	private static final int	DEPTH		= 3;

	@Override
	public void onApplicationEvent(SystemErrorEvent event) {
		String time = DateUtils.formatDate( DATA_FORMAT, new Date( event.getTimestamp() ) );
		SystemErrorException systemErrorException = event.getErrorEvnt();
		String path = PathUtil.getWebPath() + "log" + File.separator;
		File fDirectory = new File( path );
		if (!fDirectory.exists()) {
			fDirectory.mkdirs();
		}
		File f = new File( path + LOG_NAME );
		FileWriter fw = null;
		try {
			fw = new FileWriter( f, true );
			fw.write( getErrorContent( systemErrorException, time ) );
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private static final String getSystemLineChar() {
		return System.getProperty( "line.separator" );
	}

	private static final String getErrorContent(BusinessException exception, String time) {
		StackTraceElement[] sElements = exception.getStackTrace();
		int depth = sElements.length > DEPTH ? DEPTH : sElements.length;
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < depth; i++) {
			String className = sElements[ i ].getClassName();
			String methodName = sElements[ i ].getMethodName();
			int lineNumber = sElements[ i ].getLineNumber();
			String str = String.format( "[%s]%s[%s.%s]%s[%s]", time, SEPARATOR, className, methodName, SEPARATOR, lineNumber );
			if(i==0){
				sb.append( str ).append(SEPARATOR).append(String.format("%s[code=%s,message=%s]","SystemErrorException", exception.getCode(),exception.getMessage()))
				.append(getSystemLineChar());
			}else{
				sb.append( str ).append(getSystemLineChar());
			}
		}
			
		sb.append(getSystemLineChar());
		return sb.toString();
	}

}
